package ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import dataconnect.ConnectionFactory;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;

public class QuerySqlUI {

	protected Shell shell;
	private Table table_1;
	private StringBuffer endSql = new StringBuffer();
	
	private Connection con = ConnectionFactory.getConnection();
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			QuerySqlUI window = new QuerySqlUI();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		endSql.append("select number from stockanlyz where ratePercent<9 and ratePercent>0 and amountbat>2 ");
		shell = new Shell();
		
		shell.setSize(713, 529);
		shell.setText("SWT Application");
		
		shell.setMaximized(true);
		
		final SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
		sashForm.setTouchEnabled(true);
		sashForm.setBounds(10, 10, 677, 470);
		
		TextViewer textViewer = new TextViewer(sashForm, SWT.BORDER);
		final StyledText styledText = textViewer.getTextWidget();
		
		TabFolder tabFolder_1 = new TabFolder(sashForm, SWT.NONE);
		
		TabItem tabItem_1 = new TabItem(tabFolder_1, SWT.NONE);
		tabItem_1.setText("\u7ED3\u679C\u96C6");
		
		final TableViewer tableViewer_1 = new TableViewer(tabFolder_1, SWT.BORDER | SWT.FULL_SELECTION);
		table_1 = tableViewer_1.getTable();
		table_1.setHeaderVisible(true);
		table_1.setLinesVisible(true);
		tabItem_1.setControl(table_1);
		
		TabItem tabItem_2 = new TabItem(tabFolder_1, SWT.NONE);
		tabItem_2.setText("\u4FE1\u606F");
		
		TextViewer textViewer_1 = new TextViewer(tabFolder_1, SWT.BORDER);
		final StyledText styledText_1 = textViewer_1.getTextWidget();
		tabItem_2.setControl(styledText_1);
		sashForm.setWeights(new int[] {237, 254});
		final File sqlFile = new File("historydata"+File.separator+"sql.txt");
		
		final StringBuffer bstr = new StringBuffer();
		if(sqlFile.exists()){
			try {
				BufferedReader br = new BufferedReader(new FileReader(sqlFile));
				try {
					String ss ;
					while((ss= br.readLine())!=null){
						bstr.append(ss+"\n");
					}
					styledText.setText(bstr.toString());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		styledText.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				String sql = styledText.getText();
				
				try {
					FileWriter wr = new FileWriter(sqlFile);
					wr.write(sql);
					wr.flush();
					wr.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
				if(e.keyCode == SWT.F5){
					if(styledText.getSelectionText().equals("")){
						sql = styledText.getText();
						if(sql.equals("")){
							sql = endSql.toString();
						}
					}else{
						sql = styledText.getSelectionText();
					}
					
					Statement stmt = null;
					ResultSet rs =null;
					try {
						stmt = con.createStatement();
						System.out.println(sql);
						if(sql.toUpperCase().indexOf("SELECT ")>=0){
							rs = stmt.executeQuery(sql);
						}else{
							int x = stmt.executeUpdate(sql);
							styledText_1.append("\n 更新行数："+x);
							return ;
						}
						table_1.removeAll();
						int colNumber = table_1.getColumnCount();
						for (int i = colNumber-1; i>=0; i--) {
							table_1.getColumn(i).dispose();
						}
						ResultSetMetaData rsmd = rs.getMetaData();
						TableViewerColumn colIndex = new TableViewerColumn(tableViewer_1, SWT.NONE);
						TableColumn tblColindex = colIndex.getColumn();
						tblColindex.setWidth(100);
						tblColindex.setText("行");
						for (int j = 0; j < rsmd.getColumnCount(); j++) {
							TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer_1, SWT.NONE);
							TableColumn tblclmnNewColumn = tableViewerColumn.getColumn();
							tblclmnNewColumn.setWidth(100);
							tblclmnNewColumn.setText(rsmd.getColumnName(j+1));
						}
						int i=0;
						while(rs.next()){
							TableItem ti = new TableItem(table_1, SWT.NONE);
							ti.setText(0, ""+(++i));
							for (int k = 1; k <rsmd.getColumnCount()+1; k++) {
								if(rs.getObject(k)==null){
									ti.setText(k, "null");
								}else{
									ti.setText(k, rs.getObject(k).toString());
								}
							}
						}
					} catch (SQLException e1) {
						e1.printStackTrace();
						for (int i = 0; i < e1.getStackTrace().length; i++) {
							styledText_1.append(e1.getStackTrace()[i].toString()+"\n		");
						}
						return;
					} finally{
						try {
							if(rs!=null)
								rs.close();
							if(stmt!=null)
								stmt.close();
						} catch (SQLException e1) {
							e1.printStackTrace();
							return;
						}
					}
				}
			}
		});
		
		shell.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				sashForm.setBounds(10, 10, shell.getBounds().width-40, shell.getBounds().height-90);
			}
		});
	}
}
